# _*_coding:utf-8 _*_
# @Time　　:2021/6/19 22:45
# @Author : mojin
# @Email : 397135766@qq.com
# @File　　  :app_info.py
# @Software  :PyCharm
from common.logger import Logger
import os,signal,allure
import subprocess,re,time
from common.all_path import appPath ,screenPath
from common.read_yaml import ReadYaml

def exec_cmd(cmd) -> str:
    result = os.popen(cmd).read()
    return result


def get_app_name(file_dir) -> str:
    for root, dirs, files in os.walk(file_dir):
        files = [file for file in files if file.endswith(".apk")]
        if len(files) == 1:
            return files[0]
        else:
            raise FileNotFoundError("{}目录下没有测试包或者存在多个测试包。。".format(file_dir))


def get_app_package_name() -> str:
    cmd = 'aapt dump badging "{}" | findstr package'.format(os.path.join(appPath, get_app_name(appPath)))

    result = exec_cmd(cmd)

    if "package" in result:
        package_name = result.strip().split(" ")[1].split('=')[1]
        return package_name
    else:
        raise NameError("未获取到package name。")


def get_app_launchable_activity() -> str:
    cmd = 'aapt dump badging "{}" | findstr launchable'.format(os.path.join(appPath, get_app_name(appPath)))

    result = exec_cmd(cmd)

    if "launchable" in result:
        launchable_activity = result.strip().split(" ")[1].split('=')[1].replace("label", '')
        return launchable_activity
    else:
        raise NameError("未获取到launchable activity。")


def get_devices_version(device: str) -> str:
    if not isinstance(device, str):
        raise Exception("device type is should str..")
    result = exec_cmd("adb -s {} shell getprop ro.build.version.release".format(device))
    result = result.strip()
    if "error" not in result:
        return result
    else:
        raise Exception("获取设备系统版本失败，无法进行正常测试。。")





def get_all_devices_2_() -> list:
    """ 获取手机设备"""
    cmd = r'adb devices'
    #subprocess.Popen('adb kill-server', stdout=subprocess.PIPE, shell=True)
    pr = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
    pr = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
    out = pr.stdout.readlines()  # out = pr.stdout.read().decode("UTF-8")
    devices = []
    for i in (out)[1:-1]:
        device = str(i).split("\\")[0].split("'")[-1]
        devices.append(device)
    devices.sort(reverse=True)

    if len(devices) == 0:
        raise Exception("电脑未连接设备信息，无法进行正常测试。。")
    return devices




def get_all_devices() -> list:
    try:
        result = exec_cmd('adb devices')


        result = result.strip().split(" ")[3].replace("\n", '').replace("\t", ''). \
            replace("attached", '').split('device')

        result.remove('')
        if len(result) == 0:
            raise Exception("电脑未连接设备信息，无法进行正常测试。。")
        Logger.info(result)
        return  result
    except:
        return get_all_devices()


def get_device_infos_bak():
    device_infos = []
    devices = get_all_devices()
    for i in range(len(devices)):
        device_dict = {"platform_version": get_devices_version(devices[i]), "server_port": 4723 + i * 2,
                       "system_port": 8200 + i * 1, "device": devices[i]}
        device_infos.append(device_dict)

    if len(device_infos) < 1:
        raise Exception("当前电脑未连接设备信息。。。")
    Logger.info(device_infos)
    return device_infos

def get_device_infos():
    devices_info_list_data = ReadYaml("devices_info_one.yaml").get_yaml_data()  # 读取数据

    #print(devices_info_list_data)
    device_infos = []
    devices = get_all_devices()
    for i in range(len(devices)):
        device_dict = {"platform_version": get_devices_version(devices[i]), "server_port": 4723 + i * 2,
                       "system_port": 8200 + i * 1, "device": devices[i]}
        devices_info_list_data[i]['devices_list']=devices[i]
        device_infos.append([device_dict,devices_info_list_data[i]])

    if len(device_infos) < 1:
        raise Exception("当前电脑未连接设备信息。。。")
    Logger.info(device_infos)
    return device_infos

def uninstall_app(device_list: list) -> None:
    if not isinstance(device_list, list):
        raise Exception("device_list is should list!")


    for device_info in device_list:
        #cmd = 'adb -s 127.0.0.1:{} uninstall "{}"'.format(device_info.get("device").split(':')[-1], str(get_app_package_name())).replace("'", '')


        # cmd = 'adb -s {} uninstall "{}"'.format(device_info.get("device").split(':')[-1],
        #
        #                                                   str(get_app_package_name())).replace("'", '')

        cmd = 'adb -s {} uninstall "{}"'.format(device_info[0].get("device"),

                                                str(get_app_package_name())).replace("'", '')
        Logger.info("开始卸载设备上应用：{}".format(cmd))
        try:
            exec_cmd(cmd)
        except Exception as e:
            Logger.error('卸载失败！原因：%s' % (e))



def screencap_start(device,Save_screen_name='screen.mp4',time_MAX=180):
    #adb -s 3dd69892 shell screenrecord  --time-limit 180  /sdcard/screen.mp4
    command = 'adb2 -s %s shell screenrecord  --time-limit %s /sdcard/%s'%(device,time_MAX,Save_screen_name)
    Logger.info(command)

    process = subprocess.Popen(command, shell=True)
    Logger.info("开启录屏……")
    pid = process.pid
    return pid

def screencap_stop(pid,device,Save_screen_name='screen.mp4'):
    #录屏功能和运行中的
    #
    try:
        #Logger.info()
        os.kill(pid, signal.CTRL_C_EVENT)

        Logger.info("结束录屏……")
    except Exception as e:
        Logger.error('停止录屏失败！原因：%s' % (e))
    time.sleep(5)

    try:
        screenPath_mp4=os.path.join(screenPath,Save_screen_name)
        command ='adb2 -s %s  pull /sdcard/%s %s' % (device, Save_screen_name, screenPath)
        Logger.info(command)
        result = exec_cmd(command)
        Logger.info(result)
        Logger.info("录屏文件导入本地项目")
        #adb shell rm -r /sdcard/test.mp4
        # command_rm ='adb2 -s %s shell rm -r /sdcard/%s' % (device, screen_name_ipone)
        # Logger.info(command)
        # result = exec_cmd(command_rm)
        # Logger.info("删除手机录屏视频文件")
        with allure.step('测试步骤录屏'):

            allure.attach.file(screenPath_mp4, name="测试录屏",
                               attachment_type=allure.attachment_type.MP4)  # 测试步骤中添加一张图片或视频



    except Exception as e:
        Logger.error('录屏从手机导入电脑失败！原因：%s'%(e))


